package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.user.AdminConstans;
import com.heima.common.exception.CustomException;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.feign.ApAuthorFeign.ArticleFeign;
import com.heima.user.feign.WmUserFeign.WemediaFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult findListByStatus(AuthDto dto) {
        //检查参数
        if(dto==null || dto.getId()==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户不存在");
        }
        dto.checkParam();
          //封装条件 分页条件 查询条件
        Page<ApUserRealname> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        //如果状态不为空添加状态查询条件
        if(dto.getStatus()!=null){
            queryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        //执行查询
        IPage<ApUserRealname> result = page(page, queryWrapper);
        PageResponseResult responseResult = new PageResponseResult(result.getCurrent(), result.getSize(),  result.getTotal());
        responseResult.setData(result.getRecords());
        return responseResult;
    }

    @Override
    @GlobalTransactional
    public ResponseResult updateByStatus(AuthDto dto) {
        //检查参数
        if(dto==null || dto.getId()==null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(!checkStatus(dto.getStatus())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据id修改ap_user_realname的status
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(dto.getStatus());
        if(StringUtils.isNotEmpty(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg()); //审核失败原因
        }
        updateById(apUserRealname);   //修改实名认证信息
        //如果审核通过，需要同步到 wemeaia和article
        if(dto.getStatus()== AdminConstans.PASS_AUTH){
           createWmUserAndAuthor(dto.getId());
        }
        System.out.println(1/0);
        return ResponseResult.okResult();
    }

    private void createWmUserAndAuthor(Integer id){
        //获取apuser的信息，根据realname表关联的userId来查询
        ApUserRealname apUserRealname = getById(id);
        Integer userId = apUserRealname.getUserId();
        //通过userrealname的姓名和身份证号去公安系统数据库中查询是否真实存在

        //根据userId查询出ap_user
        ApUser apUser = apUserMapper.selectById(userId);
        if(apUser==null){
            throw  new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证关联用户信息不存在"));
        }
        //查询自媒体用户是否存在 如果不存在 创建wmuser保存
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if(wmUser==null){
             wmUser = new WmUser();
             wmUser.setApAuthorId(userId);
             wmUser.setName(apUser.getName());
             wmUser.setPassword(apUser.getPassword());
             wmUser.setSalt(apUser.getSalt());
             wmUser.setPhone(apUser.getPhone());
             wmUser.setStatus(9);
             wmUser.setType(0);
             wmUser.setCreatedTime(new Date());
             //保存自媒体用户
             wemediaFeign.save(wmUser);
        }
    }
    private void createAuthor(WmUser wmUser){
        //根据作者id查询作者信息是否存在
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
        //如果不存在，新建作者
        if(apAuthor==null){
             apAuthor = new ApAuthor();
             apAuthor.setName(wmUser.getName());
             apAuthor.setType(2);
             apAuthor.setUserId(wmUser.getApUserId());
             apAuthor.setWmUserId(wmUser.getId());
             articleFeign.save(apAuthor);
        }
    }
    //status必须为2或9
    public boolean checkStatus(Short status){
        if(status==null || (status!=AdminConstans.FAIL_AUTH && status!=AdminConstans.PASS_AUTH)){
            return false;
        }
        return true;
    }
}
